// AudioRecorder.js
import React, { useState, useEffect } from 'react';
import { Text, View, Button } from 'react-native';
import { Audio } from 'expo-av';

const AudioRecorder = () => {
    const [recording, setRecording] = useState(false);
    const [sound, setSound] = useState();
    const [isPlaying, setIsPlaying] = useState(false);

    useEffect(() => {
        return sound
            ? () => {
                sound.unloadAsync();
            }
            : undefined;
    }, [sound]);

    const startRecording = async () => {
        try {
            await Audio.requestPermissionsAsync();
            await Audio.setAudioModeAsync({
                allowsRecordingIOS: true,
                playsInSilentModeIOS: true,
            });
            const { recording, sound } = await Audio.Recording.createAsync(
                Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
            );
            setRecording(recording);
        } catch (error) {
            console.error('Error starting recording', error);
        }
    };

    const stopRecording = async () => {
        setRecording(false);
        if (sound) {
            sound.unloadAsync();
        }
    };

    const playSound = async () => {
        if (sound) {
            await sound.playAsync();
        } else {
            const { sound } = await Audio.Sound.createAsync(
                { uri: recording.getURI() },
                { shouldPlay: true }
            );
            setSound(sound);
        }
    };

    return (
        <View>
            <Button title={recording ? 'Stop Recording' : 'Start Recording'} onPress={recording ? stopRecording : startRecording} />
            {recording && <Text>Recording...</Text>}
            {!recording && sound && <Button title="Play Sound" onPress={playSound} />}
        </View>
    );
};

export default AudioRecorder;
